package com.ruoyi.lock.controller;

import com.google.zxing.WriterException;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.lock.domain.AppVersion;
import com.ruoyi.lock.service.IAppVersionService;
import com.ruoyi.utils.login.QRCodeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * versionController
 *
 * @author ruoyi
 * @date 2021-05-07
 */
@RestController
@RequestMapping("/app/version")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AppVersionController extends BaseController {
    private final IAppVersionService appVersionService;

    /**
     * 查询version列表
     */
    @PreAuthorize("@ss.hasPermi('app:version:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppVersion appVersion) {
        startPage();
        List<AppVersion> list = appVersionService.selectAppVersionList(appVersion);
        for (AppVersion version : list) {
            try {
                version.setCodeUrl(QRCodeUtil.createQRCode(version.getUrl()));

            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (WriterException e) {
                System.out.println(e.getMessage());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出version列表
     */
    @PreAuthorize("@ss.hasPermi('app:version:export')")
    @GetMapping("/export")
    public AjaxResult export(AppVersion appVersion) {
        List<AppVersion> list = appVersionService.selectAppVersionList(appVersion);
        ExcelUtil<AppVersion> util = new ExcelUtil<AppVersion>(AppVersion.class);
        return util.exportExcel(list, "app");
    }

    /**
     * 获取version详细信息
     */
    @PreAuthorize("@ss.hasPermi('app:version:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(appVersionService.selectAppVersionById(id));
    }

    /**
     * 新增version
     */
    @PostMapping
    public AjaxResult add(@RequestBody AppVersion appVersion)  {
//        String baseDir = FileUploadUtils.getDefaultBaseDir();
//        String filePath = "/profile/app/" + version + "/" + file.getOriginalFilename();
//
//        File newFile = new File(baseDir + filePath);
//        if (!newFile.getParentFile().exists()) {
//            newFile.getParentFile().mkdirs();
//        }
//        if (!newFile.exists()) {
//            newFile.createNewFile();
//        }
//        file.transferTo(newFile);
//        try {
//            if (file == null || file.getSize() <= 0) {
//                throw new BaseException("文件不能为空");
//            }
//            Map<String,Object> m = COSClientUtils.upload(file);
//
//            AppVersion appVersion = new AppVersion();
//            appVersion.setId(id);
//            appVersion.setName(name);
//            appVersion.setVersion(version);
//            appVersion.setUrl(m.get("url").toString());
//
//            if (appVersion.getId() != null) {
//                return toAjax(appVersionService.updateAppVersion(appVersion));
//            } else {
//                return toAjax(appVersionService.insertAppVersion(appVersion));
//            }
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//        AppVersion appVersion = new AppVersion();
//        appVersion.setId(id);
//        appVersion.setName(name);
//        appVersion.setVersion(version);
//        appVersion.setUrl(filePath);
        return toAjax(appVersionService.insertAppVersion(appVersion));
    }

    /**
     * 修改version
     */
    @PreAuthorize("@ss.hasPermi('app:version:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody AppVersion appVersion) {
        return toAjax(appVersionService.updateAppVersion(appVersion));
    }

    /**
     * 删除version
     */
    @PreAuthorize("@ss.hasPermi('app:version:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(appVersionService.deleteAppVersionByIds(ids));
    }
    /**
     * 下载 文件
     * @param response
     * @throws IOException
     */
//    @GetMapping("/downloadfile")
//    public void download(HttpServletResponse response) throws IOException {
//        // App版本
//        List<AppVersion> appVersionList = appVersionService.selectAppVersionList(null);
//        if (appVersionList != null && appVersionList.size() > 0) {
//            AppVersion appVersion = appVersionList.get(0);
//
//            String baseDir = FileUploadUtils.getDefaultBaseDir();
//            String filePath = baseDir + appVersion.getUrl();
//            File file = new File(filePath);
//            if (!file.exists()) {
//                response.getWriter().print("file is not exists");
//                return;
//            }
//
//            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
//
//            byte[] buffer = new byte[1024];
//            try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) {
//                OutputStream os = response.getOutputStream();
//                response.setContentLengthLong(fis.available());
//
//                int i = bis.read(buffer);
//                while (i != -1) {
//                    os.write(buffer, 0, i);
//                    i = bis.read(buffer);
//                }
//                os.flush();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

//    @GetMapping("/downloadfile")
//    public void download(HttpServletResponse response) throws IOException {
//        // App版本
//        List<AppVersion> appVersionList = appVersionService.selectAppVersionList(null);
//        if (appVersionList != null && appVersionList.size() > 0) {
//            AppVersion appVersion = appVersionList.get(0);
//            try {
//                String wjurl=appVersion.getUrl();
//                //String wjurl = urlByLoanid.get("url");
//                int i = wjurl.lastIndexOf("/");
//                String fileName = wjurl.substring(i+1);
//
//                URL url = new URL(wjurl);
//                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//                //设置超时间为3秒
//                conn.setConnectTimeout(3*1000);
//                //防止屏蔽程序抓取而返回403错误
//                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//                //得到输入流
//                InputStream inputStream = conn.getInputStream();
//                //获取自己数组
//                byte[] bs = readInputStream(inputStream);
//                response.setContentType("application/octet-stream;charset=ISO8859-1");
//                BufferedOutputStream output = null;
//                BufferedInputStream input = null;
//                try {
//                    output = new BufferedOutputStream(response.getOutputStream());
//                    // 中文文件名必须转码为 ISO8859-1,否则为乱码
//                    String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
//                    // 作为附件下载
//                    response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
//
//                    output.write(bs);
//                    response.flushBuffer();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } // 用户可能取消了下载
//                finally {
//                    if (input != null)
//                        try {
//                            input.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    if (output != null)
//                        try {
//                            output.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    /**
     * 下载 文件
     * @param url
     * @param response
     * @throws IOException
     */
   /* @GetMapping("/downloadByUrl")
    public void download2(@RequestParam("url") String url, HttpServletResponse response) throws IOException {
        String baseDir = FileUploadUtils.getDefaultBaseDir();
        String filePath = baseDir + url;
        File file = new File(filePath);
        if (!file.exists()) {
            response.getWriter().print("file is not exists");
            return;
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
    }
*/
    /**
     * 下载 文件 （腾讯云COS）
     * 返回文件下载地址
     * @param response
     * @throws IOException
     */
//    @GetMapping("/COSDownloadfile")
//    public AjaxResult COSDownloadfile(HttpServletResponse response) throws IOException {
//        // App版本
//        List<AppVersion> appVersionList = appVersionService.selectAppVersionList(null);
//        if (appVersionList != null && appVersionList.size() > 0) {
//            AppVersion appVersion = appVersionList.get(0);
//            MangheDownload mangheDownload = new MangheDownload();
//            mangheDownload.setUrl(appVersion.getUrl());
//            mangheDownload.setVersion(appVersion.getVersion());
//            mangheDownload.setCreateTime(new Date());
//            mangheDownload.setCreateBy(null);
//            mangheDownloadService.insertMangheDownload(mangheDownload);
//            return AjaxResult.success(appVersion.getUrl());
//        }
//        return AjaxResult.error("没有可下载的文件");
//    }
    /**
     * 检查版本
     *
     * @param appVersion 返回最新版本
     * @return
     */
//    @PreAuthorize("@ss.hasPermi('app:version:check')")
    @GetMapping("/check")
    public AjaxResult checkVersion(AppVersion appVersion) {
        String version = appVersion.getVersion();
        return AjaxResult.success(appVersionService.checkVersion(version));
    }

    /**
     * 下载 文件
     * @param response
     * @throws IOException
     */
    @Anonymous
    @GetMapping("/downloadfile")
    public void download(HttpServletResponse response) throws IOException {
        // App版本
        List<AppVersion> appVersionList = appVersionService.selectAppVersionList(null);
        if (appVersionList != null && appVersionList.size() > 0) {
            AppVersion appVersion = appVersionList.get(0);

            String baseDir = FileUploadUtils.getDefaultBaseDir();
            String filePath = baseDir + appVersion.getUrl();
            File file = new File(filePath);
            if (!file.exists()) {
                response.getWriter().print("file is not exists");
                return;
            }

            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            byte[] buffer = new byte[1024];
            try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) {
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                os.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载 文件
     * @param url
     * @param response
     * @throws IOException
     */
    @GetMapping("/downloadByUrl")
    public void download(@RequestParam("url") String url, HttpServletResponse response) throws IOException {
        String baseDir = FileUploadUtils.getDefaultBaseDir();
        String filePath = baseDir + url;
        File file = new File(filePath);
        if (!file.exists()) {
            response.getWriter().print("file is not exists");
            return;
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
